const express        = require('express');
const router = express.Router();

var xlsxj = require("xlsx-to-json");
var multer  = require('multer')
var cors = require('cors');

const fse = require('fs-extra') 
const crypto = require('crypto');    

function parse(req, res, next){
    var file = req.file;
    xlsxj({
            input: req.file.path, 
            output: `output/util/xlsx/${new Date().getTime()}_${req.file.filename}.json`
            }, 
            function(err, result) {
                if(err) {
                    res.send(err);
                }else {
                    req.xlsx2json = result;
                    next();
                }
        });
}

router.use(cors())

var uploadXlsx = multer({ dest: './uploads/util/xlsx/' })
router.post('/api/parsexlsx', uploadXlsx.single('file'), parse, (req, res, next)=>{
    res.send({code: 200, result: req.xlsx2json});
});


var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/util/pdf/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
// var uploadPdf = multer({ dest: 'uploads/util/pdf/' });
var uploadPdf = multer({ storage: storage });
router.post('/api/uploadpdf', uploadPdf.array('files'), (req, res, next) => {
    //originalname
    //filename
    //path
    if(req.files.length == 0){
        res.send({code: 0, message: 'upload at least one file!'});
    }

    var accPath = '../../public/upload/mailAcc';
    var hash = crypto.createHmac('sha256', req.files[0].filename)
                        .digest('hex').substring(0,16);
    var ts = new Date().getTime();
    var toPath = `${accPath}/${hash}_${ts}`;

    try{
        for(var i=0; i<req.files.length; i++){

            var oriFilePath = `${req.files[i].path}`;
            fse.copySync(oriFilePath, `${toPath}/${req.files[i].filename}`);
                // .then(() => {
                //     res.send({code: 200, message: "上传成功"})
                // })
                // .catch(err => {
                //     res.send({code: 500, message: "server err"})
                // })
        }
        res.send({code: 200, message: "上传成功"})
    }catch(e){
        res.send({code: 500, message: "server err", e: e})
    }

})

module.exports = router;